import PaginationBar from "../../components/paginationbar";
import React, {useEffect, useState} from 'react'
import {Breadcrumb, Button, Col,Select , Form, Input, Modal, Pagination, Row, Space,} from 'antd'
import common from "../../common"
import Table from "antd/es/table"

function Workshop(props) {
    let initSearch = {}
    let [dataList, setDataList] = useState([])
    let [workshopList, setWorkshopList] = useState([])
    let [search, setSearch] = useState(initSearch)       // 搜索内容
    let [query, setQuery] = useState(initSearch);

    const [searchForm] = Form.useForm();
    let [pagination, setPagination] = useState({
        total: 0,
        page: 1,
        limit: 10,
    })
    const {Option} = Select;

    let [createModalVisible, setCreateModalVisible] = useState(false)
    let [editModalVisible, setEditModalVisible] = useState(false)
    let [createForm] = Form.useForm();
    let [editForm] = Form.useForm();
    let [users, setUsers] = useState([]);
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '名字',
            dataIndex: 'name',
        },
        {
            title: '负责人姓名',
            dataIndex: 'userName',
        },
        {
            title: '操作',
            align: "center",
            width: 160,
            fixed: "right",
            render: (text, record, index) => {
                return (
                    <>
                        <Button type="link" onClick={() => {
                            setEditModalVisible(true)
                            editForm.setFieldsValue(record)
                        }}>编辑</Button>
                        <Button type="link" onClick={() => {
                            common.confirm("确定要删除吗?", () => {
                                del(record.id)
                            })
                        }}>删除</Button>
                    </>
                )
            }
        }
    ];

    // 获取车间列表
    const getWorkshops = () => {
        let params = {
            ...search,
            page: pagination.page,
            limit: pagination.limit,
        }
        common.ajax("GET", "/front/workshop/list", params).then(data => {
            setDataList(data.list)
            setPagination(data.pagination)
        })
    }
    // 获取负责人
    const getUsers = () => {
        common.ajax("GET", "/passport/user/list?limit=100").then(data => {
            setUsers(data.list)
        })
    }
// 获取车间列表
    const getAllWorkshops = () => {
        common.ajax("GET", "/front/workshop/list").then(data => {
            setWorkshopList(data.list)
        })
    }
    function searchName(value) {
        setSearch({...search, name: value})
        getWorkshops()
        console.log(`selected ${value}`);
    }

    function searchUserName(value) {
        setSearch({...search, userId: value})
        console.log(`selected ${value}`);
    }

    const create = (data) => {
        common.loadingStart()
        common.ajax("POST", "/front/workshop/create", data).then(res => {
            common.toast("操作成功")
            setCreateModalVisible(false)
            getWorkshops()
        }).finally(common.loadingStop)
    }

    const update = (data) => {
        common.loadingStart()
        common.ajax("POST", "/front/workshop/update", data).then(res => {
            common.toast("操作成功")
            setEditModalVisible(false)
            getWorkshops()
        }).finally(common.loadingStop)
    }

    const del = (id) => {
        common.loadingStart()
        common.ajax("POST", "/front/workshop/delete", {id}).then(res => {
            common.toast("操作成功")
            getWorkshops()
        }).finally(common.loadingStop)
    }

    useEffect(() => {
        getWorkshops()
        getUsers()
        getAllWorkshops()
    }, [pagination.page, pagination.limit,search])

    return (
        <div className="Workshop">
            <Breadcrumb>
                <Breadcrumb.Item>设备管理</Breadcrumb.Item>
                <Breadcrumb.Item>车间管理</Breadcrumb.Item>
            </Breadcrumb>
            <div style={{padding: 24, minHeight: 600}}>
                <div>
                    <Button type="primary" onClick={() => {
                        setCreateModalVisible(true)
                        createForm.setFieldsValue({title: ""})
                    }}>新增</Button>
                </div>

                <Form  form={searchForm}  style={{marginTop: 15}}>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="车间名字" name="name">
                                <Input placeholder="名字"  onChange={(e) => {
                                    setQuery({...query,name: e.target.value})
                                }}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="负责人姓名" name="userId">
                                <Select  placeholder="负责人"  onChange={(value) => {
                                    setQuery({...query,userId: value})
                                }}>
                                    {users.map(item => {
                                        return (<Option key={item.id} value={item.id} > {item.name}</Option>)
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item>
                                <Space>
                                    <Button onClick={() => {
                                        setSearch(query)
                                    }}>搜索</Button>
                                    <Button onClick={() => {
                                        let emptySearch = {
                                            name: '',
                                            userId: '',
                                        }
                                        searchForm.setFieldsValue(emptySearch)
                                        emptySearch = {}
                                        setSearch(emptySearch)
                                        setQuery(emptySearch)
                                    }}>清空</Button>
                                </Space>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>

                <Table rowKey={columns => columns.id} dataSource={dataList} columns={columns} pagination={false}/>

                {pagination.total < 5 ? '' :
                    <PaginationBar>
                        <Pagination
                            style={{marginTop: 25}}
                            pageSizeOptions={['10', '20', '50', '100']}
                            onChange={(page, limit) => {
                                setPagination({...pagination, page, limit})
                            }}
                            onShowSizeChange={(page, limit) => {
                                setPagination({...pagination, page, limit})
                            }}
                            showTotal={total => `共${total}条`}
                            total={pagination.total}
                            defaultCurrent={pagination.page}
                            current={pagination.page}
                            defaultPageSize={pagination.limit}
                            showSizeChanger
                            showQuickJumper
                        /></PaginationBar>}

            </div>

            <Modal title="新增" destroyOnClose={true} footer={false} maskClosable={false} visible={createModalVisible}
                   onCancel={() => {
                       setCreateModalVisible(false)
                   }}
            >
                <Form preserve={false}
                      labelCol={{span: 4}}
                      wrapperCol={{span: 20}}
                      form={createForm}
                      onFinish={(values) => {
                          create(values)
                      }}
                >

                    <Form.Item
                        label="车间名字"
                        name="name"
                        rules={[{required: true, message: '请输入车间名称'}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="负责人"
                        name="userId"
                        rules={[{required: true, message: '请选择负责人'}]}
                    >
                        <Select  placeholder="姓名" >
                            {users.map(item => {
                                return (<Option key={item.id} value={item.id} > {item.name}</Option>)
                            })}
                        </Select>
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 4, span: 20}}>
                        <Button type="primary" htmlType="submit">
                            保存
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal title="编辑" footer={false} maskClosable={false} visible={editModalVisible} onCancel={() => {
                setEditModalVisible(false)
            }}
            >
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 20}}
                    form={editForm}
                    onFinish={(values) => {
                        update(values)
                    }}
                >

                    <Form.Item
                        hidden={true}
                        name="id"
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="车间名字"
                        name="name"
                        rules={[{required: true, message: '请输入车间名字'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        label="负责人"
                        name="userId"
                        rules={[{required: true, message: '请输入负责人姓名'}]}
                    >
                        <Select  placeholder="姓名" >
                            {users.map(item => {
                                return (<Option key={item.id} value={item.id} > {item.name}</Option>)
                            })}
                        </Select>
                    </Form.Item>

                    <Form.Item wrapperCol={{offset: 4, span: 20}}>
                        <Button type="primary" htmlType="submit">
                            保存
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

        </div>
    );
}

export default Workshop
